<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="_submit"
    @cancel="_cancel">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['userId', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item v-show="title == '新建用户'" label="商户">
          <a-select
            placeholder="请选择商户"
            v-decorator="['merchantId', { rules: [{ required: true, message: '请选择商户，商户不能为空！' }] }]"
          >
            <a-select-option :value="item.merchantId" v-for="item in merchantSelList" :key="item.merchantId">
              {{ item.merchantName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="姓名">
          <a-input v-decorator="['userName', { rules: [{ required: true, message: '姓名不能为空!' }] }]" />
        </a-form-item>
        <a-form-item label="手机号码">
          <a-input
            :maxLength="11"
            v-decorator="['mobile', { rules: [{ required: true, message: '手机号码不能为空!' }] }]"
          />
        </a-form-item>
        <a-form-item label="职务">
          <a-input v-decorator="['userJob', { rules: [{ required: true, message: '职务不能为空!' }] }]" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { getMerchantSelList } from '@/api/common'

// 表单字段
const fields = ['merchantId', 'userId', 'userName', 'mobile', 'userJob']

export default {
  props: {
    title: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    checkedKeys: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      merchantSelList: [],
      form: this.$form.createForm(this)
    }
  },
  methods: {
    /**
     * 提交表单
     */
    _submit: function () {
      this.$emit('ok')
    },
    /**
     * 取消
     */
    _cancel: function () {
      this.$emit('cancel')
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  mounted () {
    if (this.title === '新建用户') {
      getMerchantSelList({})
        .then((res) => {
          this.merchantSelList = res.dataList
        })
        .catch((e) => {})
    }
  }
}
</script>
